package com.xike.net;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.xike.util.MLog;
import com.xike.util.Manager;
import com.xike.util.StringUtil;

public final class ApacheClient extends HttpClient {
	private static final String TAG = "ApacheClient:";
	private DefaultHttpClient httpclient;
	private boolean hasCacheHomeFileDir = true;

	public ApacheClient() {
		super();
	}

	@Override
	public void init(String cacheFilePath) {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, NetConstant.CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, NetConstant.CONNECTION_TIMEOUT);
		httpclient = new DefaultHttpClient(params);
		ClientConnectionManager mgr = httpclient.getConnectionManager();
		httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);

		if (cacheFilePath == null || cacheFilePath.equals("")) {
			hasCacheHomeFileDir = false;
			MLog.e(TAG, "ERROR: cacheFileHomePath is null!");
		}
	}

	@Override
	public void init() {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, NetConstant.CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, NetConstant.CONNECTION_TIMEOUT);
		httpclient = new DefaultHttpClient(params);
	}

	@Override
	protected int doMethod(int method) {
		HttpUriRequest request;
		String cacheFilePath = "";
		String urlString = url.toString();
		MLog.e("ApacheClient url", urlString);
		long currentDate = System.currentTimeMillis() / 1000;

		int result = 0;
		try {
			urlMd5 = StringUtil.MD5(urlString);
			if (useCache && Manager.useNetCache && hasCacheHomeFileDir) {
				cacheFilePath = Manager.getCACHE_DATA_DIR() + urlMd5;

				if (Manager.fileSp.contains(urlMd5)) {
					File file = new File(cacheFilePath);
					if (currentDate - Manager.fileSp.getLong(urlMd5, 0) < NetConstant.NET_CACHE_SECONDS) {
						// 如果缓存中有此url，且未过期，且文件存在，且文件>0，则直接返回 从文件中解析
						if (file.exists() && file.length() > 0) {
							MLog.e(TAG, "get inputStream from file");
							MLog.e(TAG, "fileName:" + urlMd5);
							is = new FileInputStream(file);
							result = HttpClient.NET_SUCCESS;
							return result;
						}
					}
					// 缓存过期，文件不存在，或者文件为0
					file.delete();
					Manager.fileSpEditor.remove(urlMd5);
					Manager.fileSpEditor.commit();
				}
			}

			// 如果缓存中有此url但时间戳过期或者无缓存，则访问此url
			MLog.e(TAG, "get inputStream from url");

			if (method == HttpClient.HTTP_METHOD_POST) {
				// POST请求
				if (Manager.isUseProxy()) {
					int queryStart = urlString.indexOf('/', 7);
					request = new HttpPost(Manager.getNetProxy() + urlString.substring(queryStart));
					request.setHeader("X-Online-Host", urlString.substring(7, queryStart));
				} else {
					request = new HttpPost(urlString);
				}

				UrlEncodedFormEntity entityIn = new UrlEncodedFormEntity(postData, NetConstant.DEFAULT_CONTENT_CHARSET);
				((HttpPost) request).setEntity(entityIn);
			} else {
				// GET请求
				if (Manager.isUseProxy()) {
					int queryStart = urlString.indexOf('/', 7);
					request = new HttpGet(Manager.getNetProxy() + urlString.substring(queryStart));
					request.setHeader("X-Online-Host", urlString.substring(7, queryStart));
				} else {
					request = new HttpGet(urlString);
				}
			}

			// 设置通用Header参数
			if (useDefaultHeader) {
				for (BasicHeader header : defaultHeaders) {
					request.addHeader(header.getName(), header.getValue());
				}
			}
			HttpResponse response = httpclient.execute(request);

			result = response.getStatusLine().getStatusCode();
			HttpEntity entityOut = response.getEntity();
			if (entityOut != null) {
				Header contentEncodingHeader = entityOut.getContentEncoding();
				if (contentEncodingHeader != null) {
					contentEncoding = contentEncodingHeader.getValue();
				} else {
					contentEncoding = null;
				}
				contentLength = entityOut.getContentLength();
				is = entityOut.getContent();

				if (result == HttpClient.NET_SUCCESS) {
					// 将此流读入文件并保存此url
					if (useCache && Manager.useNetCache && hasCacheHomeFileDir) {
						MLog.e("cacheFilePath", "" + cacheFilePath);
						if (toFile(cacheFilePath)) {
							Manager.fileSpEditor.putLong(urlMd5, currentDate);
							Manager.fileSpEditor.commit();
						}
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			close();
			result = HttpClient.NET_ENCODING_ERROR;
		} catch (ClientProtocolException e) {
			close();
			result = HttpClient.NET_CLIENT_PROTOCOL_ERROR;
		} catch (IOException e) {
			close();
			result = HttpClient.NET_IO_ERROR;
			e.printStackTrace();
		} catch (Exception e) {
			result = HttpClient.NET_UNKONWN_ERROR;
			close();
			e.printStackTrace();
		} finally {
			// do nothing
		}

		return result;
	}

	@Override
	protected void close() {
		shutdownHttpClient();
	}

	private void shutdownHttpClient() {
		if (httpclient != null && httpclient.getConnectionManager() != null) {
			httpclient.getConnectionManager().shutdown();
		}

	}
}